package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public Result queryShopById(Long id) {
        /*String cashShop = stringRedisTemplate.opsForValue()
                .get(RedisConstants.CACHE_SHOP_KEY + id);
        if (StrUtil.isNotBlank(cashShop)) {
            Shop shop = JSONUtil.toBean(cashShop, Shop.class);
            return shop;
        }
        Shop shop = shopMapper.selectById(id);
        if (shop != null) {
            stringRedisTemplate.opsForValue()
                    .set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop));
        }
        return shop;*/

        // 互斥锁实现避免缓存击穿
        Shop shop = new Shop();
        String cashShop = stringRedisTemplate.opsForValue()
                .get(RedisConstants.CACHE_SHOP_KEY + id);
        if (StrUtil.isNotBlank(cashShop)) {
            shop = JSONUtil.toBean(cashShop, Shop.class);
            return Result.ok(shop);
        }
        // 获取锁
        try {
            if (redisUtils.tryLock(RedisConstants.LOCK_SHOP_KEY + id, id.toString(), RedisConstants.LOCK_SHOP_TTL)) {
                shop = shopMapper.selectById(id);
                stringRedisTemplate.opsForValue()
                        .set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.SECONDS);
                redisUtils.unlock(RedisConstants.LOCK_SHOP_KEY + id);
            } else {
                Thread.sleep(500);
                queryShopById(id);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Result.ok(shop);
    }
}
